<template>
  <div class="dynamic_form_item">
    <a-form-item :name="props.question.key">
      <template v-slot:label>
        <label for="">{{ props.question.label }}</label>
        <a-tooltip  v-if="props.question.state.tipText" :key="props.question.label" :title="props.question.state.tipText" >
          <i class="iconfont" :style="{ marginLeft: '8px' }" :class="props.question.state.tipIconClassName"></i>
        </a-tooltip>
      </template>
      <template v-if="props.config.isView">
        <span v-if="props.question.state.labelKey">{{ showKeyName(props.dataForm, props.question.state.labelKey) }}</span>
        <span v-else>{{ staticView }}</span>
      </template>
      <template v-else>
        <a-radio-group v-model:value="props.question.value" @change="selectQs" :disabled="props.question.disabled">
          <a-radio v-for="(item, index) in props.question.options" :value="item.value" :key="index">
            <a-input :index="index" class="radio_label_input" v-if="item.type === 'input'" v-model.value="item.typeValue"></a-input>
            {{ item.label }}
          </a-radio>
        </a-radio-group>
      </template>
    </a-form-item>
  </div>
</template>

<script setup lang="ts">
import { watch, getCurrentInstance, onMounted, onUnmounted, computed } from 'vue';
import { QuestionBase } from '../../../question-base';
import { filter } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { isHidden } from '@/utils';
import { INFOSERVE, RADIOSERVE, RESETVERIFY } from '@/mixins/subject/subject-types';
import { formInfoStore } from '@/store/modules/form';
import { paramsData, showKeyName } from '@/components/public-template/publicMethod';
// import dictionary from '@/filters/dictionary';
import { getDictionaryList } from '@/utils/dictionary';
import localDictionary from '@/filters/dictionary';
const formStore = formInfoStore();
let dictionary = formStore.getDictionary;

//subject变量
let $subscribeSub: Subscription;

const { proxy }: any = getCurrentInstance();
let props = defineProps<{ question: QuestionBase<any>; formData: any; config: any; dataForm: any }>();
const emit = defineEmits(['update:formData']);
watch(
  () => props.question.value,
  (val) => {
    emit('update:formData', val);
  },
  { flush: 'sync' }
);

onMounted(() => {
  init();
  //自动执行以下下拉
  if (props.question.state.autoPerform) {
    selectQs(props.question.value);
  }
  subWatch();
});

//解绑
onUnmounted(() => {
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
  }
});

//静态数据
const staticView = computed(() => {
  if (props.question.value || props.question.value === 0) {
    let data = props.question.options.find((res) => res.value === props.question.value);
    if (data) {
      return data.label;
    }
  }
});

function init(data: any = null) {
  console.log('这里', data);
  //控制options的控制
  if (data && props.question.state.optionsTerms) {
    props.question.options.forEach((item: any) => {
      item.show = isHidden(data, item);
    });
  }
  //给options里面的typeValue赋值
  if (data && props.question.optionsValue) {
    props.question.options.forEach((item: any) => {
      if (item.key) {
        item.typeValue = data[item.key];
      }
    });
  }

  //取配置信息
  if (props.question.type === 'dictionary') {
    if (props.question.state.url) {
      getDictionaryList(props.question.state, (res) => {
        props.question.options = res;
      });
      return;
    }
    let dicObj: any = dictionary[props.question.state.filterName] || localDictionary[props.question.state.filterName];
    let arr: any = [];
    for (const key in dicObj) {
      if (dicObj.hasOwnProperty(+key)) {
        arr.push({
          label: dicObj[key],
          value: props.question.state.valueType === 'string' ? key + '' : +key
        });
      }
    }
    props.question.options = arr;
  }
  selectAction();

}

//监听动态表单数据完成
const subWatch = () => {
  $subscribeSub = proxy.$NotificationFormSub
    .getParams()
    .pipe(filter((res: any) => res !== 0))
    .subscribe((item: any) => {
      try {
        if (item.key === INFOSERVE) {
          //数据都全部都到了
          if (item.value) {
            init(item.value[props.question.key]);
          }
          //自动执行以下下拉
          if (props.question.state.autoPerform) {
            selectQs(props.question.value);
          }
        }
      } catch (error) {}
    });
};

function selectQs(key: any) {
  switch (key) {
    case 'individuation':
      break;
    default:
      clearOptionsValue(key);
      proxy.$NotificationFormSub.pushParams({
        key: RADIOSERVE,
        value: {
          key: props.question.key,
          value: props.question.value,
          name: props.question.state.name || ''
        }
      });
      break;
  }
  selectAction();
}
function clearOptionsValue(val: any) {
  if (props.question.optionsValue) {
    props.question.options.forEach((item: any) => {
      if (item.key && val !== item.value) {
        item.typeValue = '';
      }
    });
  }
}

//选择灵动
const selectAction = () => {
  console.log('选择数据');
  //控制form参数
  if (props.question.state && props.question.state.changeOptions && !props.question.hidden) {
    updateOptions(props.question.state.changeOptions[props.question.value] || props.question.state.changeOptions['default']);
  }
  //自动灵动更新同级组件属性并初始化
  if (props.question.state.changeAuto && props.question.value !== null) {
    let data = props.question.options.find((res) => res.value === props.question.value);
    let options = [];
    if (data && !props.question.state.offChangeAuto) {
      for (const key in props.question.state.changeAuto) {
        if (props.question.state.changeAuto[key]) {
          options.push({
            key,
            option: props.question.state.changeAuto[key]?.option || 'state.params',
            value:
              typeof props.question.state.changeAuto[key].value === 'string'
                ? data[props.question.state.changeAuto[key].value]
                : paramsData(data, { params: props.question.state.changeAuto[key].value })
          });
        }
      }
    }
    options.length && updateOptions(options);
    console.log('选中的值', options, data);
  }
  //选中后带上额外参数一起提交
  extendParams();
};

//更新云数据
const updateOptions = (arr: any = []) => {
  const formStore = formInfoStore();
  if (props.question.state.type === 'layer' || props.config.type === 'layer') {
    formStore.updateLayerQuestions(arr);
  }
  formStore.updateQuestions(arr);
  //动态改变表单
  proxy.$NotificationFormSub.pushParams({ key: RESETVERIFY, value: { name: 'form' } });
};

//扩展字段
const extendParams = () => {
  if (props.question.state.changeParams && props.question.value) {
    let data = props.question.options.find((res) => (typeof props.question.value === 'object' ? props.question.value.includes(res.value) : res.value === props.question.value));
    let params = paramsData(data, { params: props.question.state.changeParams });
    props.question.state.extendParams = params;
    console.log('看下参数', props.question.state);
  }
};
</script>

<style lang="less" scoped>
@import url('./input-radio.component.less');
</style>
